package com.kafka.demo.config.yml;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class KafkaProducerProperties {

    private String bootstrapServers;

    private String keySerializer = "org.apache.kafka.common.serialization.StringSerializer";
    private String valueSerializer = "org.apache.kafka.common.serialization.StringSerializer";

    private String acks;
    private Integer retries;
    private String batchSize;
    private String bufferMemory;
    private Integer lingerMs;
    private Integer requestTimeoutMs;
    private Integer connectionTimeoutMs;

    // 转换工具方法
    public long getBufferMemoryInBytes() {
        return parseDataSize(bufferMemory);
    }

    public int getBatchSizeInBytes() {
        return (int) parseDataSize(batchSize);
    }

    private long parseDataSize(String size) {
        if (size == null || size.isEmpty()) {
            throw new IllegalArgumentException("Data size string cannot be null or empty");
        }

        size = size.trim().toUpperCase();

        // 匹配数字和单位
        Pattern pattern = Pattern.compile("^([0-9]+)([A-Z]+)?$");
        Matcher matcher = pattern.matcher(size);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid data size format: " + size);
        }

        long value = Long.parseLong(matcher.group(1));
        String unit = matcher.group(2); // KB, MB, etc.

        switch (unit) {
            case "":
            case "B":
                return value;
            case "KB":
            case "KIB":
                return value * 1024;
            case "MB":
            case "MIB":
                return value * 1024 * 1024;
            case "GB":
            case "GIB":
                return value * 1024 * 1024 * 1024;
            default:
                throw new IllegalArgumentException("Unsupported data unit: " + unit);
        }
    }
}